package com.github.kezhenxu94.playground.java.concurrent.itc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <pre>
 * 
 * {@link CyclicBarrier} - 栅栏
 * 
 * 栅栏功能与闭锁相似，除了栅栏可以重置而闭锁不能重置。
 * 
 * </pre>
 * 
 * @author kezhenxu
 *
 */
public class StudyCyclicBarrier {

	public static void main(String[] args) throws Exception {
		final CyclicBarrier barrier = new CyclicBarrier(10,
				() -> System.out.println(Thread.currentThread() + " Pass action"));
		final ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < 9; i++) {
			exec.execute(() -> {
				try {
					barrier.await();
					System.out.println(Thread.currentThread() + " passed the barrier");
				} catch (InterruptedException | BrokenBarrierException e) {
					e.printStackTrace();
				}
			});
		}
		Thread.sleep(3000);
		barrier.await();

		exec.shutdown();
	}
}
